/**
 * jims
 */
package com.jims.master.modules.patient.myRecord.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.WebServiceUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.patient.myRecord.dao.CaseReportDao;
import com.jims.master.modules.patient.myRecord.entity.*;
import com.jims.master.modules.sys.entity.HospitalDict;
import com.jims.master.modules.sys.service.HospitalDictService;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Service
 * @author chentao
 * @version 2017-06-17
 */
@Service
@Transactional(readOnly = true)
public class CaseReportService extends CrudService<CaseReportDao, CaseReport> {

    @Autowired
    private HospitalDictService hospitalDictService;
    @Autowired
    private CaseReportFileService caseReportFileService;
    @Autowired
    private CasePrescService casePrescService;
    @Autowired
    private CaseEnterHospitalService caseEnterHospitalService;
    @Autowired
    private CaseDiagnosisService caseDiagnosisService;
    @Autowired
    private CasePrescriptionService casePrescriptionService;
    @Autowired
    private CasePrescriptionDetailsService casePrescriptionDetailsService;
    @Autowired
    private CaseClinicCaseService caseClinicCaseService;
    @Autowired
    private CaseClinicDiagnosisService caseClinicDiagnosisService;


	@Override
    public CaseReport get(String id) {
		return super.get(id);
	}

	@Override
    public List<CaseReport> findList(CaseReport caseReport) {
		return super.findList(caseReport);
	}

	@Override
    public Page<CaseReport> findPage(Page<CaseReport> page, CaseReport caseReport) {
		return super.findPage(page, caseReport);
	}

	@Override
    @Transactional(readOnly = false)
	public int save(CaseReport caseReport) {
		return super.save(caseReport);
	}

	@Override
    @Transactional(readOnly = false)
	public int delete(CaseReport caseReport) {
		return super.delete(caseReport);
	}

	/**
	 * 根据多条件查询病人病历信息
	 * @param caseReport
     * @author chentao
	 * @return
	 */
	public List<CaseReport> getCaseReport(CaseReport caseReport){
        List<CaseReport> caseReportList = dao.getCaseReport(caseReport);
        for(int i = 0; i < caseReportList.size(); i++){
            //存放图片地址集合
            List fileUrlist = new ArrayList();
            //存放文件地址集合
            List fileMoreUrlList = new ArrayList();
            //健康档案详情表集合
            List<CaseReportFile> caseReportFileList = caseReportList.get(i).getCaseReportFileList();
            if(caseReportFileList.size()>0&&caseReportFileList.get(0)!=null){
                if(caseReportFileList.get(0).getFileUrl()!=null&&caseReportFileList.get(0).getFileUrl()!=""){
                    //取出图片路径截取放入集合
                   String a[] = caseReportFileList.get(0).getFileUrl().split(",");
                    for (int j = 0; j < a.length; j++){
                        fileUrlist.add(a[j]);
                    }
                    caseReportFileList.get(0).setFileUrlList(fileUrlist);
                }
                if(caseReportFileList.get(0).getFileMoreUrl()!=null&&caseReportFileList.get(0).getFileMoreUrl()!=""){
                    //取出文件路径截取放入集合
                    String b[] = caseReportFileList.get(0).getFileMoreUrl().split(",");
                    for (int l = 0; l < b.length; l++){
                        fileMoreUrlList.add(b[l]);
                    }
                    caseReportFileList.get(0).setFileMoreUrlList(fileMoreUrlList);
                }
            }
        }
		return caseReportList;
	}

    /**
     * 添加病例
     * @param caseReport
     * @param caseReportFile
     * @author chentao
     * @return
     */
    @Transactional(readOnly = false)
    public int saveRecord(CaseReport caseReport, CaseReportFile caseReportFile){
        int i = 0;
        this.save(caseReport);
        caseReportFile.setCaseReportId(caseReport.getId());
        i = caseReportFileService.save(caseReportFile);
        return i;
    }
    /**
     * 根据身份证查询病历信息
     * @param caseReport
     * @return
     */
    public List<CaseReport> getCaseReportUpdate(CaseReport caseReport){
        return dao.getCaseReportUpdate(caseReport);
    }

    /**
     * 根据双滦his存储
     * @param result
     * @param orgId
     */
    @Transactional(readOnly = false)
    public void clinicFromHis(BaseDto result,String orgId) {
        CaseReport caseReportQuery = new CaseReport();
        //根据clinicId查询是否已经同步此条门诊记录
        String clinicid = (String) result.get("id");
        caseReportQuery.setClinicId(clinicid);
        caseReportQuery = dao.getCaseReportByClinicId(caseReportQuery);
        if (caseReportQuery == null) {
            //没有此条数据准备插入数据
            CaseReport caseReport = new CaseReport();
            caseReport.setBaseinfo(UserUtils.getUser().getPersionId());
            //同步时间
            caseReport.setPreDate(new Date());
            //病例类型  1.门诊病历
            caseReport.setMedicalType("1");
            caseReport.setType("1");
            caseReport.setSex((String) result.get("sex"));
            caseReport.setAge((String) result.get("age"));
            caseReport.setClinicId(clinicid);
            caseReport.setVisitDate(DateUtils.parseDate(result.get("visit_date") + " 00:00:00"));
            caseReport.setVisitDept((String) result.get("dept_name"));
            caseReport.setDoctor((String) result.get("doctor_name"));
            caseReport.setOrgId(orgId);
            HospitalDict hospitalDict = new HospitalDict();
            hospitalDict.setOrgId(orgId);
            hospitalDict = hospitalDictService.getHospitalDictsByEntity(hospitalDict);
            caseReport.setOrgName(hospitalDict.getLabel());
            caseReport.setDelFlag("0");
            save(caseReport);
            CaseReportFile caseReportFile = new CaseReportFile();
            caseReportFile.setCaseReportId(caseReport.getId());
            caseReportFileService.save(caseReportFile);
            //根据clinicId同步门诊处方信息
            BaseDto baseDto = new BaseDto();
            baseDto.put("clinicid", clinicid);
            List<BaseDto> params = new ArrayList<BaseDto>();
            params.add(baseDto);
            List<BaseDto> prescriptionList = WebServiceUtils.getExamList(orgId, "/api/prescription/list", params);
            if (prescriptionList != null && prescriptionList.size() > 0) {
                for (int i=0; i<prescriptionList.size();i++){
                    //处方主表case_prescription
                    CasePrescription casePrescription = new CasePrescription();
                    casePrescription.setId((String) prescriptionList.get(i).get("id"));
                    casePrescription.setApplyOn((String) prescriptionList.get(i).get("apply_on"));
                    casePrescription.setBillingPop((String) prescriptionList.get(i).get("billing_pop"));
                    casePrescription.setBillingDept((String) prescriptionList.get(i).get("billing_dept"));
                    casePrescription.setClinicId((String) prescriptionList.get(i).get("clinic_id"));
                    casePrescription.setVisitId((String) prescriptionList.get(i).get("visit_id"));
                    casePrescription.setItemClass((String) prescriptionList.get(i).get("item_class"));
                    casePrescription.setBillingDate((String) prescriptionList.get(i).get("billing_date"));
                    casePrescriptionService.insert(casePrescription);
                    //处方明细表详情
                    List<BaseDto> prescriptionDetailsList = (List<BaseDto>) prescriptionList.get(i).get("itemlist");
                    if (prescriptionDetailsList != null && prescriptionDetailsList.size() > 0) {
                        for (int j = 0; j<prescriptionDetailsList.size();j++){
                            //处方明细case_prescription_details
                            Map b = prescriptionDetailsList.get(j);
                            CasePrescriptionDetails casePrescriptionDetails = new CasePrescriptionDetails();
                            casePrescriptionDetails.setDrugCode((String) b.get("drug_code"));
                            casePrescriptionDetails.setUnit((String) b.get("unit"));
                            casePrescriptionDetails.setSpec((String) b.get("spec"));
                            casePrescriptionDetails.setAdministration((String) b.get("administration"));
                            Double num = (Double) b.get("num");
                            casePrescriptionDetails.setNum(num+"");
                            casePrescriptionDetails.setPackageSpec((String) b.get("package_spec"));
                            casePrescriptionDetails.setDrugName((String) b.get("drug_name"));
                            casePrescriptionDetails.setFreqDesc((String) b.get("freq_desc"));
                            casePrescriptionDetails.setPackageUnit((String) b.get("package_unit"));
                            casePrescriptionDetails.setApplyId((String) b.get("apply_id"));
                            casePrescriptionDetails.setFirmName((String) b.get("firm_name"));
                            casePrescriptionDetailsService.save(casePrescriptionDetails);
                        }
                    }
                }
            }
            //根据clinicId同步门诊病历信息
/*            BaseDto baseDto1 = new BaseDto();
            baseDto1.put("clinicid", clinicid);
            List<BaseDto> params1 = new ArrayList<BaseDto>();
            params1.add(baseDto1);*/
            BaseDto caseBaseDto = WebServiceUtils.getExamEngit(orgId, "/api/clinicRecord/get", params);
            //门诊病历表
            CaseClinicCase caseClinicCase  = new CaseClinicCase();
            caseClinicCase.setClinicId(caseBaseDto.getAsString("clinic_id"));
            caseClinicCase.setMaibo(caseBaseDto.getAsString("maibo"));
            caseClinicCase.setXueya(caseBaseDto.getAsString("xueya"));
            caseClinicCase.setHunyushi(caseBaseDto.getAsString("hunyushi"));
            caseClinicCase.setFuzhujiancha(caseBaseDto.getAsString("fuzhujiancha"));
            caseClinicCase.setTiwen(caseBaseDto.getAsString("tiwen"));
            caseClinicCase.setXianbingshi(caseBaseDto.getAsString("xianbingshi"));
            caseClinicCase.setJiazushi(caseBaseDto.getAsString("jiazushi"));
            caseClinicCase.setHuxi(caseBaseDto.getAsString("huxi"));
            caseClinicCase.setZhusu(caseBaseDto.getAsString("zhusu"));
            caseClinicCase.setXiaojieyufenxi(caseBaseDto.getAsString("xiaojiefenxi"));
            caseClinicCase.setJiwangshi(caseBaseDto.getAsString("jiwangshi"));
            caseClinicCaseService.save(caseClinicCase);
            //根据clinicId同步诊断信息
/*            BaseDto baseDto2 = new BaseDto();
            baseDto2.put("clinicid", clinicid);
            List<BaseDto> params2 = new ArrayList<BaseDto>();
            params2.add(baseDto2);*/
            List<BaseDto> diagnosisList = WebServiceUtils.getExamList(orgId, "/api/diagnosis/list", params);
            if (diagnosisList != null && diagnosisList.size() > 0) {
                for (int i=0; i<diagnosisList.size();i++){
                    //诊断表case_clinic_diagnosis
                    CaseClinicDiagnosis caseClinicDiagnosis = new CaseClinicDiagnosis();
                    caseClinicDiagnosis.setClinicId(diagnosisList.get(i).getAsString("clinic_id"));
                    caseClinicDiagnosis.setDiagnosisDate(DateUtils.parseDate(diagnosisList.get(i).get("diagnosis_date")));
                    caseClinicDiagnosis.setDiagnosisId(diagnosisList.get(i).getAsString("icd_code"));
                    caseClinicDiagnosis.setName(diagnosisList.get(i).getAsString("icd_name"));
                    caseClinicDiagnosisService.save(caseClinicDiagnosis);
                }
            }
        }
    }
    /**
     * 根据HIS数据保存
     * @param—BaseDto
     * @return
     */
    @Transactional(readOnly = false)
    public void upDateMyRecordFromHis(BaseDto result,String orgId){
        //住院患者caseReport
        for(Map casereportMap:(ArrayList<Map>)result.get("resultpatientvisitlist")){
            CaseReport caseReport = new CaseReport();
            caseReport.setBaseinfo(UserUtils.getUser().getPersionId());
            caseReport.setVisitDate(DateUtils.parseDate(casereportMap.get("ruyuan_date") + " 00:00:00"));
            caseReport.setPreDate(new Date());
            caseReport.setType("1");
            caseReport.setCaseNo((String)casereportMap.get("inpno"));
            caseReport.setMedicalType("0");
            caseReport.setOrgId(orgId);
            HospitalDict hospitalDict = new HospitalDict();
            hospitalDict.setOrgId(orgId);
            hospitalDict = hospitalDictService.getHospitalDictsByEntity(hospitalDict);
            caseReport.setOrgName(hospitalDict.getLabel());
            caseReport.setDelFlag("0");
            save(caseReport);
        }
        //门诊信息caseReport
        for(Map casereportMap:(ArrayList<Map>)result.get("resultclinicmasterlist")){
            CaseReport caseReport = new CaseReport();
            caseReport.setBaseinfo(UserUtils.getUser().getPersionId());
            caseReport.setVisitDate(DateUtils.parseDate(casereportMap.get("visit_date") + " 00:00:00"));
            caseReport.setPreDate(new Date());
            caseReport.setType("1");
            caseReport.setCaseNo((String) casereportMap.get("clinic_no"));
            caseReport.setClinicId((String) casereportMap.get("clinic_id"));
            caseReport.setVisitDept((String)casereportMap.get("dept_name"));
            caseReport.setDoctor((String) casereportMap.get("doctorstr"));
            caseReport.setMedicalType("1");
            caseReport.setOrgId(orgId);
            HospitalDict hospitalDict = new HospitalDict();
            hospitalDict.setOrgId(orgId);
            hospitalDict = hospitalDictService.getHospitalDictsByEntity(hospitalDict);
            caseReport.setOrgName(hospitalDict.getLabel());
            caseReport.setDelFlag("0");
            save(caseReport);
        }
        //医真结果CaseReportFile
        for(Map casereportFileMap:(ArrayList<Map>)result.get("resultexamreportlist")){
            //if("1".equals((String)casereportFileMap.get("type"))){
                CaseReportFile caseReportFile = new CaseReportFile();
                caseReportFile.setCcessionno((String)casereportFileMap.get("ccessionno"));
                caseReportFile.setFileType("1");
                caseReportFile.setCaseNo((String) casereportFileMap.get("clinicno"));
                caseReportFile.setFileUrl((String) casereportFileMap.get("reportpath"));
                caseReportFile.setApplyDoctor((String) casereportFileMap.get("doctorname"));
                CaseReport caseReport = new CaseReport();
                caseReport.setBaseinfo(UserUtils.getUser().getPersionId());
                caseReport.setCaseNo((String) casereportFileMap.get("clinicno"));
                caseReport.setMedicalType((String)casereportFileMap.get("type"));
                CaseReport caseReportDb = getMainCaseReportUpdate(caseReport);
                if(caseReportDb!=null)
                    caseReportFile.setCaseReportId(caseReportDb.getId());
                caseReportFile.setReportTime(DateUtils.parseDate(casereportFileMap.get("reporttime")));
                caseReportFileService.save(caseReportFile) ;
            //}
        }
        //处方主表caseReportFile
        for(Map casereportMapOutpPresc:(ArrayList<Map>)result.get("resultoutpprescmain")){
            CaseReportFile caseReportFile = new CaseReportFile();
            caseReportFile.setCcessionno((String) casereportMapOutpPresc.get("prescno"));
            caseReportFile.setFileType("2");
            caseReportFile.setCaseNo((String) casereportMapOutpPresc.get("clinicno"));
            caseReportFile.setClinicId((String) casereportMapOutpPresc.get("clinicid"));
            CaseReport caseReport = new CaseReport();
            caseReport.setBaseinfo(UserUtils.getUser().getPersionId());
            caseReport.setCaseNo((String) casereportMapOutpPresc.get("clinicno"));
            caseReport.setMedicalType("1");
            CaseReport caseReportDb = getMainCaseReportUpdate(caseReport);
            if(caseReportDb!=null)
                caseReportFile.setCaseReportId(caseReportDb.getId());
            caseReportFileService.save(caseReportFile) ;
        }
        //处方明细case_presc
        for(Map casereportMapOutpPrescDetail:(ArrayList<Map>)result.get("resultoutppresc")){
            CasePresc casePresc = new CasePresc();
            casePresc.setDrugName((String) casereportMapOutpPrescDetail.get("drugname"));
            casePresc.setFirmIdName((String) casereportMapOutpPrescDetail.get("firmname"));
            casePresc.setAmount(String.valueOf((Integer) casereportMapOutpPrescDetail.get("amount")));
            casePresc.setUnits((String) casereportMapOutpPrescDetail.get("units"));
            casePresc.setDrugSpec((String) casereportMapOutpPrescDetail.get("drugspec"));
            casePresc.setDosage((String)casereportMapOutpPrescDetail.get("dosage"));
            casePresc.setDosageUnits((String) casereportMapOutpPrescDetail.get("dosageunits"));
            //casePresc.setCosts(String.valueOf((Double) casereportMapOutpPrescDetail.get("costs")));
            casePresc.setAdministration((String) casereportMapOutpPrescDetail.get("administrationstr"));
            casePresc.setFrequency((String) casereportMapOutpPrescDetail.get("frequencystr"));
            casePresc.setPrescNo((String) casereportMapOutpPrescDetail.get("prescno"));
            casePresc.setSerialNo((String) casereportMapOutpPrescDetail.get("serialno"));
            casePresc.setItemNo(String.valueOf((Integer)  casereportMapOutpPrescDetail.get("itemno")));
            casePrescService.save(casePresc) ;
        }
        //常规记录CaseEnterHospital
        for(Map casereportMapEnterHospital:(ArrayList<Map>)result.get("resultenterhospital")){
            CaseEnterHospital caseEnterHospital = new CaseEnterHospital();
            caseEnterHospital.setZhusu((String) casereportMapEnterHospital.get("zhusu"));
            caseEnterHospital.setXianbingshi((String) casereportMapEnterHospital.get("xianbingshi"));
            caseEnterHospital.setJiwangshi((String) casereportMapEnterHospital.get("jiwangshi"));
            caseEnterHospital.setJiazushi((String) casereportMapEnterHospital.get("jiazushi"));
            caseEnterHospital.setHunyushi((String) casereportMapEnterHospital.get("hunyushi"));
            caseEnterHospital.setFuzhujiancha((String) casereportMapEnterHospital.get("fuzhujiancha"));
            caseEnterHospital.setXiaojieyufenxi((String) casereportMapEnterHospital.get("xiaojieyufenxi"));
            caseEnterHospital.setClinicId((String) casereportMapEnterHospital.get("clinicid"));
            caseEnterHospitalService.save(caseEnterHospital) ;
        }
        //诊断CaseDiagnosis
        for(Map casereportMapDiagnosis:(ArrayList<Map>)result.get("resultdiagnosis")){
            CaseDiagnosis caseDiagnosis = new CaseDiagnosis();
            caseDiagnosis.setDiagnosisId((String) casereportMapDiagnosis.get("icdname"));
            CaseEnterHospital caseEnterHospital = new CaseEnterHospital();
            caseEnterHospital.setClinicId((String) casereportMapDiagnosis.get("clinicid"));
            CaseEnterHospital caseEnterHospitalDB =caseEnterHospitalService.getByClinicId(caseEnterHospital);
            if(caseEnterHospitalDB!=null)
                caseDiagnosis.setParentId(caseEnterHospitalDB.getId());
            caseDiagnosisService.save(caseDiagnosis) ;
        }
    }

    /***
     * 根据身份证和入院日期查询病历主表信息
     * @param caseReport
     * @return
     */
    public CaseReport getMainCaseReportUpdate(CaseReport caseReport){
        return dao.getMainCaseReportUpdate(caseReport);
    }

    /***
     * 根据clinicId查询病历主表信息
     * @param caseReport
     * @return
     * */
    public CaseReport getCaseReportByClinicId(CaseReport caseReport){
        return dao.getCaseReportByClinicId(caseReport);
    }

    /***
     * 查找病历权限
     * @param caseReport
     * @return
     * */
    public CaseReport getRecordRight(CaseReport caseReport){
        return dao.getRecordRight(caseReport);
    }
    /***
     * 保存病历权限
     * @param caseReport
     * @return
     * */
    @Transactional(readOnly = false)
    public int saveRecordRight(CaseReport caseReport){
        return dao.saveRecordRight(caseReport);
    }
    /***
     * 保存病历权限
     * @param caseReport
     * @return
     * */
    @Transactional(readOnly = false)
    public int updateRecordRight(CaseReport caseReport){
        return dao.updateRecordRight(caseReport);
    }
	
}